package com.ghostmonk.text
{
	import caurina.transitions.Tweener;
	
	import flash.text.*;

	public class EmbeddedText extends TextField
	{
		private var _format:TextFormat;
		
		private var _fieldHeight:Number;
		
		public function get fieldHeight():Number
		{
			return _fieldHeight;
		}
		
		public function get format():TextFormat
		{
			return _format;
		}
		
		public function setFormat():void
		{
		 	defaultTextFormat = _format;	
		}
		
		public function setFontSize(value:int):void
		{
			format.size = value;
			setFormat();
		}
		
		public function set color(value:uint):void
		{
			format.color = value;
			setTextFormat(format);
		}
		
		public function EmbeddedText(font:String, size:Number, color:Number, singleLineAuto:Boolean = false, embed:Boolean = true)
		{
			_fieldHeight = 0;
			_format = new TextFormat(font, size, color);
			_format.align = TextFormatAlign.LEFT;
			
			defaultTextFormat = _format;
			
			selectable = false;
			mouseEnabled = false;
			embedFonts = embed;
			gridFitType = GridFitType.PIXEL;
			
			if(singleLineAuto)
			{
				setSingleAuto();
			}
			else
			{
				defaultFormat();
			}
		}
		
		public function testMetrics(txt:String, maxHeight:Number, maxFontSize:int):void
		{
			format.size = maxFontSize;
			defaultTextFormat = format;
			
			var currentSize:int = maxFontSize;
			testSize(txt);
			while(testSize(txt) > maxHeight)
			{
				format.size = currentSize--;
				defaultTextFormat = format;	
			}	
			Tweener.addTween(this, {_text:txt, time:0.5, transition:'linear'});
		}
		
		private function testSize(txt:String):Number
		{
			text = txt;
			var h:Number = height;
			text = "";
			_fieldHeight = h;
			return h;
		}
		
		private function defaultFormat():void
		{
			autoSize = TextFieldAutoSize.LEFT;
			multiline = true;
			wordWrap = true;
		}
		
		private function setSingleAuto():void
		{
			width = 0;
			multiline = false;
			wordWrap = false;
			autoSize = TextFieldAutoSize.LEFT;
		}
		
	}
}